﻿using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;

namespace CORE
{
    public class Utils
    {
        public static String GetTitle(string chuoi)
        {
            string[] VietnameseSigns = new string[]
         {
          "aAeEoOuUiIdDyY",
          "áàạảãâấầậẩẫăắằặẳẵ",
          "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",
          "éèẹẻẽêếềệểễ",
          "ÉÈẸẺẼÊẾỀỆỂỄ",
          "óòọỏõôốồộổỗơớờợởỡ",
          "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",
          "úùụủũưứừựửữ",
          "ÚÙỤỦŨƯỨỪỰỬỮ",
          "íìịỉĩ",
          "ÍÌỊỈĨ",
          "đ",
          "Đ",
          "ýỳỵỷỹ",
          "ÝỲỴỶỸ"
         };
            string str = chuoi.ToLower();
            for (int i = 1; i < VietnameseSigns.Length; i++)
            {
                for (int j = 0; j < VietnameseSigns[i].Length; j++)
                    str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
            }
            String a = str;
            a = a.Replace(" ", "-").Replace("?", "").Replace(".", "").Replace("&", "").Replace("''", "").Replace(",", "").Replace("\"", "").Replace("/", "-").Replace("--", "-").Replace("(", "-").Replace(")", "-");
            a = Regex.Replace(a, "--", "-");
            return a;

        }
        public static string RemoveSign4VietnameseString(string str)
        {

            //Tiến hành thay thế , lọc bỏ dấu cho chuỗi
            for (int i = 1; i < VietnameseSigns.Length; i++)
            {
                for (int j = 0; j < VietnameseSigns[i].Length; j++)
                    str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
            }
            return str;
        }
        private static readonly string[] VietnameseSigns = new string[]
     {
      "aAeEoOuUiIdDyY",
      "áàạảãâấầậẩẫăắằặẳẵ",
      "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",
      "éèẹẻẽêếềệểễ",
      "ÉÈẸẺẼÊẾỀỆỂỄ",
      "óòọỏõôốồộổỗơớờợởỡ",
      "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",
      "úùụủũưứừựửữ",
      "ÚÙỤỦŨƯỨỪỰỬỮ",
      "íìịỉĩ",
      "ÍÌỊỈĨ",
      "đ",
      "Đ",
      "ýỳỵỷỹ",
      "ÝỲỴỶỸ"
     };

        public static int getIntQuery(string id)
        {
            int number;
            if (HttpContext.Current.Request.QueryString[id] != null)
            {
                if ((!Int32.TryParse(HttpContext.Current.Request.QueryString[id].ToString(), out number)))
                {
                    return 0;
                }
                return int.Parse(HttpContext.Current.Request.QueryString[id].ToString());
            }
            return 0;
        }
        public static String getStringQuery(string id)
        {

            if (HttpContext.Current.Request.QueryString[id] != null)
            {

                return HttpContext.Current.Request.QueryString[id].ToString();
            }
            return "";
        }
        public static String getStringFrom(string id)
        {

            if (HttpContext.Current.Request.Form[id] != null)
            {

                return HttpContext.Current.Request.Form[id].ToString();
            }
            return "";
        }
        public static int getIntFrom(string id)
        {
            int number;
            if (HttpContext.Current.Request.Form[id] != null)
            {
                if ((!Int32.TryParse(HttpContext.Current.Request.Form[id].ToString(), out number)))
                {
                    return 0;
                }
                return int.Parse(HttpContext.Current.Request.Form[id].ToString());
            }
            return 0;
        }
        public static String getStringSession(String txt)
        {
            if (HttpContext.Current.Session[txt] != null)
            {
                return HttpContext.Current.Session[txt].ToString();
            }
            return "";
        }
        public static int getIntSession(String txt)
        {
            int number;
            if (HttpContext.Current.Session[txt] != null)
            {
                if ((!Int32.TryParse(HttpContext.Current.Session[txt].ToString(), out number)))
                {
                    return 0;
                }
                return Int32.Parse(HttpContext.Current.Session[txt].ToString());
            }
            return 0;
        }

        public static string getMD5(string txt)
        {
            string source = txt;
            MD5 md5 = MD5.Create();
            string hash = GetMd5Hash(md5, source);
            return hash;
        }

        static string GetMd5Hash(MD5 md5Hash, string input)
        {

            // Convert the input string to a byte array and compute the hash. 
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes 
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data  
            // and format each one as a hexadecimal string. 
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string. 
            return sBuilder.ToString();
        }

        // Verify a hash against a string. 
        static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
        {
            // Hash the input. 
            string hashOfInput = GetMd5Hash(md5Hash, input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public string sendMail(string mail_nguoi_gui, string ten_nguoi_gui, string tieu_de, String noi_dung, string mail_nguoi_nhan)
        {

            DateTime localTime = DateTime.Now;
            string timeString24Hour = localTime.ToString("HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
            string body = "test send mail1" + timeString24Hour;
            string host = "";
            int post = 0;
            post = 587;
            host = "mail.dtctech.com.vn";
            string cc = "phuoc.nuce@gmail.com";
            mailMessage.From = (new System.Net.Mail.MailAddress("phuoc@dtctech.com.vn", "CDQN", System.Text.Encoding.UTF8));
            mailMessage.To.Add(mail_nguoi_nhan);

            //mailMessage.To.Add(mail_nguoi_gui);


            // mailMessage.Bcc.Add(cc);

            mailMessage.Subject = tieu_de;
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            mailMessage.IsBodyHtml = true;
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential();
            mailAuthentication.UserName = "phuoc@dtctech.com.vn";
            mailAuthentication.Password = "Abc12345a";
            SmtpClient mailClient = new SmtpClient("mail.dtctech.com.vn");
            mailClient.EnableSsl = false;
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            mailClient.Credentials = mailAuthentication;
            mailMessage.Body = noi_dung;
            try
            {
                mailClient.Send(mailMessage);

            }
            catch
            {
                return "";
            }
            return "2";
        }
        public static string SendMail(string tomail, string subject)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();
            string msg = string.Empty;
            //try
            //{
            MailAddress fromAddress = new MailAddress("congsinhvien@dhpd.edu.vn");
            message.From = fromAddress;
            message.To.Add(tomail);

            message.Subject = "Quên mật khẩu";
            message.IsBodyHtml = true;
            message.Body = subject;
            smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("congsinhvien@dhpd.edu.vn", "phuoc12345");

            smtpClient.Send(message);
            msg = "Successful<BR>";
            //}
            //catch (Exception ex)
            //{
            //    msg = ex.Message;
            //}
            return msg;
        }
        public static string SendMail(string tomail, string subject, string body)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();
            string msg = string.Empty;
            try
            {
                MailAddress fromAddress = new MailAddress("congsinhviendhpd3@gmail.com");
                message.From = fromAddress;
                message.To.Add(tomail);

                message.Subject = subject;
                message.IsBodyHtml = true;
                message.Body = body;
                smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
                smtpClient.Port = 587;
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials = new System.Net.NetworkCredential("congsinhviendhpd3@gmail.com", "phuoc12345");

                smtpClient.Send(message);
                msg = "Successful<BR>";
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }
        public static string SendMail(List<String> tomail, string subject, string body)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();
            string msg = string.Empty;
            try
            {
                MailAddress fromAddress = new MailAddress("congsinhvien@dhpd.edu.vn");
                message.From = fromAddress;
                foreach (string item in tomail)
                {
                    message.To.Add(item);
                }
                // message.To.Add("hongphuoc8912@gmail.com");
                message.Subject = subject;
                message.IsBodyHtml = true;
                message.Body = body;
                smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
                //  smtpClient.Port = 587;
                smtpClient.EnableSsl = true;
                // smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials = new System.Net.NetworkCredential("congsinhvien@dhpd.edu.vn", "phuoc12345");

                smtpClient.Send(message);
                msg = "Successful<BR>";
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }
        public static string SendMail(List<String> tomail, string body)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();
            string msg = string.Empty;
            try
            {
                MailAddress fromAddress = new MailAddress("congsinhvien@dhpd.edu.vn");
                message.From = fromAddress;
                foreach (string item in tomail)
                {
                    message.To.Add(item);
                }
                // message.To.Add("hongphuoc8912@gmail.com");
                message.Subject = "Thắc mắc điểm" + DateTime.Now.ToString("ddmmyyhh");
                message.IsBodyHtml = true;
                message.Body = body;
                smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
                smtpClient.Port = 587;
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials = new System.Net.NetworkCredential("congsinhvien@dhpd.edu.vn", "phuoc12345");
                smtpClient.Send(message);
                msg = "Successful<BR>";
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }
        public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[62];
            chars =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }

        public static void checkupdate()
        {
            string flag = WebConfigurationManager.AppSettings["flag_update"].ToString();
            if (flag == "1")
            {
                if (Utils.getStringSession("userid") == "")
                    HttpContext.Current.Response.Redirect("/capnhat.aspx");
            }
        }
    }
}
